package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.entity.SystemConfig;
import com.example.smartwaterapi.service.SystemConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统配置控制器
 */
@Tag(name = "系统配置管理API", description = "系统配置相关接口")
@RestController
@RequestMapping("/api")
public class SystemConfigController {

    @Autowired
    private SystemConfigService systemConfigService;

    @Operation(summary = "获取系统配置详情", description = "根据ID获取系统配置信息")
    @GetMapping("/system/config/{id}")
    public RestApiResponse<SystemConfig> getSystemConfig(@Parameter(description = "ID") @PathVariable Integer id) {
        SystemConfig config = systemConfigService.getById(id);
        if (config == null) {
            return RestApiResponse.notFound("系统配置记录不存在");
        }
        return RestApiResponse.ok(config);
    }

    // Add more endpoints
    
    /**
     * 前端系统配置接口
     */
    @Operation(summary = "获取所有系统配置", description = "获取所有系统配置信息，按组分类")
    @GetMapping("/system/config")
    public RestApiResponse<Map<String, Object>> getAllSystemConfigs() {
        List<SystemConfig> configs = systemConfigService.list();
        
        // 将配置按组分类
        Map<String, List<SystemConfig>> groupedConfigs = configs.stream()
                .collect(Collectors.groupingBy(SystemConfig::getGroupName));
        
        // 将配置值转换为合适的格式
        Map<String, Object> result = new HashMap<>();
        
        for (Map.Entry<String, List<SystemConfig>> entry : groupedConfigs.entrySet()) {
            String group = entry.getKey();
            Map<String, Object> groupConfig = new HashMap<>();
            
            for (SystemConfig config : entry.getValue()) {
                groupConfig.put(config.getConfigKey(), config.getConfigValue());
            }
            
            result.put(group, groupConfig);
        }
        
        return RestApiResponse.ok(result);
    }
} 